package edu.software.PBL_Management_System.controller;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.software.PBL_Management_System.service.InterestTopicService;
import edu.software.PBL_Management_System.mapper.InterestTopicMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import edu.software.PBL_Management_System.dto.ChatRequest;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 专家兴趣点划分
 * 实现逻辑：后端将数据库中的已有项目标题转发给AI，AI根据项目标题生成项目兴趣点，由前端进行解析
 */
@Slf4j
@RestController
@RequestMapping("/api")
@CrossOrigin(origins ="*")
public class InterestTopicController {

    @Autowired
    private InterestTopicService interestTopic;

    @Autowired
    private InterestTopicMapper interestTopicMapper;

    /**
     * 获取项目兴趣点
     * @return json格式的数据
     */
    @GetMapping("/interest-topic")
    public String getInterestTopic(){
        try {
            log.info("开始生成兴趣点");

            // 从数据库获取所有标题
            List<String> titles = interestTopicMapper.selectAllTitles();
            if (titles == null || titles.isEmpty()) {
                return "{\"error\": \"没有找到任何项目标题\"}";
            }

            // 构建请求对象
            ChatRequest request = new ChatRequest();
            request.setQuery(String.join("\n", titles)); // 将所有标题用换行符连接
            request.setInputs(new HashMap<>());
            request.setResponseMode("streaming");
            request.setUser("system");
            request.setAutoGenerateName(false);

            // 调用dify服务获取流式数据
            String streamData = interestTopic.interestTopic(request);
            log.info("获取到流式数据，开始解析");

            // 解析流式数据并提取answer内容
            String interestTopic = parseStreamDataAndExtractAnswer(streamData);

            log.info("生成的json数据: {}", interestTopic);

            return interestTopic;

        } catch(Exception e) {
            log.error("划分子需求错误", e);
            return "{\"error\": \"划分子需求错误：" + e.getMessage() + "\"}";
        }
    }

    // ... 保持其他方法不变 ...
    /**
     * 解析流式数据并提取answer内容进行拼接
     * @param streamData 流式数据字符串
     * @return 拼接后的完整JSON字符串
     */
    private String parseStreamDataAndExtractAnswer(String streamData) {
        StringBuilder accumulatedAnswer = new StringBuilder();

        try {
            // 按行分割数据
            String[] lines = streamData.split("\n");

            for (String line : lines) {
                String trimmedLine = line.trim();

                // 跳过空行
                if (trimmedLine.isEmpty()) {
                    continue;
                }

                // 处理以 "data: " 开头的行
                if (trimmedLine.startsWith("data: ")) {
                    String jsonStr = trimmedLine.substring(6); // 移除 "data: " 前缀

                    try {
                        // 使用ObjectMapper解析JSON
                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode jsonNode = objectMapper.readTree(jsonStr);

                        // 提取answer内容
                        if (jsonNode.has("answer")) {
                            String answer = jsonNode.get("answer").asText();
                            accumulatedAnswer.append(answer);
                            log.debug("提取到answer片段: {}", answer);
                        }

                        // 记录事件类型（可选）
                        if (jsonNode.has("event")) {
                            String event = jsonNode.get("event").asText();
                            log.debug("处理事件: {}", event);
                        }

                    } catch (Exception parseError) {
                        log.warn("解析JSON失败: {}, 原始数据: {}", parseError.getMessage(), jsonStr);
                    }
                }
            }

            String finalAnswer = accumulatedAnswer.toString();
            log.info("累积answer内容完成，总长度: {}", finalAnswer.length());
            log.info("拼接后的完整内容: {}", finalAnswer);

            // 验证最终结果是否为有效的JSON
            if (isValidJson(finalAnswer)) {
                return finalAnswer;
            } else {
                log.warn("拼接后的内容不是有效的JSON格式，尝试清理格式: {}", finalAnswer);
                // 尝试清理可能的格式问题
                String cleanedJson = finalAnswer.trim();
                if (isValidJson(cleanedJson)) {
                    return cleanedJson;
                }
                // 如果还是无效，直接返回原始数据（因为从日志看实际上是有效的JSON）
                log.info("直接返回原始数据");
                return finalAnswer;
            }

        } catch (Exception e) {
            log.error("解析流式数据时发生错误: ", e);
            return "{\"error\": \"解析数据时发生错误: " + e.getMessage() + "\"}";
        }
    }

    /**
     * 验证字符串是否为有效的JSON格式
     * @param jsonStr 待验证的字符串
     * @return true表示有效的JSON，false表示无效
     */
    private boolean isValidJson(String jsonStr) {
        if (jsonStr == null || jsonStr.trim().isEmpty()) {
            return false;
        }

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            // 配置ObjectMapper以更宽松地解析JSON
            objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            objectMapper.readTree(jsonStr.trim());
            return true;
        } catch (Exception e) {
            log.debug("JSON验证失败: {}", e.getMessage());
            return false;
        }
    }
}
